package com.mayikt.main.consumer;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.main.api.impl.entity.SysUserLoginLog;
import com.mayikt.main.api.impl.mapper.SysUserLoginLogMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 * @author 余胜军
 * @ClassName UniqueLoginConsumer2
 * @qq 644064779
 * @addres www.mayikt.com
 * 微信:yushengjun644
 */
@Component
@Slf4j
public class UniqueLoginBatchConsumer {
    @Autowired
    private SysUserLoginLogMapper sysUserLoginLogMapper;

    @RabbitHandler
    @RabbitListener(queues = "fanout_wechattemplate_queue")
    @Transactional
    public void process(String msg, Channel channel, Message message) throws IOException {
        log.info("开始批量处理:msgs{}", msg);
        List<SysUserLoginLog> sysUserLoginLogs = JSONObject.parseArray(msg, SysUserLoginLog.class);
        try {
            // 采用mybatis 批量插入数据
            int result = sysUserLoginLogMapper.batchInsert(sysUserLoginLogs);
            log.info("<batchInsert result:{} >", result);
        } catch (Exception e) {
            log.error("<e:{}>", e);
            // 将异常消息记录下来 后期补偿
        } finally {
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            channel.basicAck(deliveryTag, true);// 手动ack成功 发送通知给 mq服务器端说 消费成功了 msg 从mq服务器端删除
        }
        // 只有异常的情况下 才会不断重试重试!

    }
}